package cn.tedu.boot42.controller;

import cn.tedu.boot42.vo.User;
import cn.tedu.boot42.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/check")
    @ResponseBody
    public int check(String username){
        User user = mapper.selectByUsername(username);
        if(user!=null){
            return 2;
        }
        return 1;
    }

    @RequestMapping("/reg")
    @ResponseBody
    public int reg(User user){
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            return 2;
        }
        mapper.insert(user);
        return 1;
    }

    @RequestMapping("login")
    @ResponseBody
    public int login(User user, String rem, HttpServletResponse response, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            if(u.getPassword().equals(user.getPassword())){
                //登录成功时把当前登录的用户信息保存到回话对象中
                //保存到Session里面的数据可以共享给当前客户端的其他请求
                session.setAttribute("u",u);
                if(rem!=null){
                    Cookie c1 = new Cookie("username", user.getUsername());
                    Cookie c2 = new Cookie("password", user.getPassword());
                    //保存一个月
                    c1.setMaxAge(60*60*24*30);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                return 1;
            }else{
                return 3;
            }
        }
        return 2;

    }

    @RequestMapping("/currentUser")
    @ResponseBody
    public User currentUser(HttpSession session){
        //去登录成功时保存的用户对象
        return (User) session.getAttribute("u");
    }

    @RequestMapping("/logout")
    @ResponseBody
    public void logout(HttpSession session){
        //删除登录成功时的用户对象
        session.removeAttribute("u");
    }
}
